<!-- 评论管理页面 - 提供评论的审核、回复、删除等功能，支持批量操作 -->
<template>
  <div class="comment-list">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">评论管理</h2>
      <div class="header-actions">
        <!-- 批量通过按钮 -->
        <el-button type="success" @click="batchApprove" :disabled="selectedComments.length === 0">
          批量通过
        </el-button>
        <!-- 批量拒绝按钮 -->
        <el-button type="danger" @click="batchReject" :disabled="selectedComments.length === 0">
          批量拒绝
        </el-button>
      </div>
    </div>

    <!-- 示例数据提示 -->
    <el-alert v-if="isUsingSampleData" title="示例数据模式" type="warning" :closable="false" show-icon>
      <template #default>
        当前正在使用示例数据，后端API调用失败。请检查后端服务是否正常运行。
      </template>
    </el-alert>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <!-- 搜索输入框 -->
      <el-input v-model="searchKeyword" placeholder="搜索评论内容..." class="search-input" clearable @input="handleSearch">
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>

      <!-- 状态筛选 -->
      <el-select v-model="selectedStatus" placeholder="选择状态" clearable @change="handleFilter">
        <el-option label="待审核" value="pending" />
        <el-option label="已通过" value="approved" />
        <el-option label="已拒绝" value="rejected" />
      </el-select>

      <!-- 文章筛选 -->
      <el-select v-model="selectedPost" placeholder="选择文章" clearable @change="handleFilter">
        <el-option v-for="post in posts" :key="post.id" :label="post.title" :value="post.id" />
      </el-select>
    </div>

    <!-- 评论列表表格 -->
    <el-table :data="filteredComments" @selection-change="handleSelectionChange" style="width: 100%"
      v-loading="isLoading">
      <!-- 多选列 -->
      <el-table-column type="selection" width="55" />

      <!-- 评论内容列 -->
      <el-table-column prop="content" label="评论内容" min-width="300">
        <template #default="{ row }">
          <div class="comment-content">
            <p class="comment-text">{{ row.content }}</p>
            <div class="comment-meta">
              <span class="comment-author">{{ row.author }}</span>
              <span class="comment-time">{{ formatDate(row.createTime) }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 文章列 -->
      <el-table-column prop="postTitle" label="文章" width="200">
        <template #default="{ row }">
          <el-link type="primary" @click="viewPost(row.postId)">
            {{ row.postTitle }}
          </el-link>
        </template>
      </el-table-column>

      <!-- 状态列 -->
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作列 - 固定在右侧 -->
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <!-- 通过按钮 - 仅对待审核评论显示 -->
            <el-button v-if="row.status === 'pending'" size="small" type="success" plain class="action-btn"
              @click="approveComment(row.id)">
              <el-icon>
                <Check />
              </el-icon>
              通过
            </el-button>
            <!-- 拒绝按钮 - 仅对待审核评论显示 -->
            <el-button v-if="row.status === 'pending'" size="small" type="danger" plain class="action-btn"
              @click="rejectComment(row.id)">
              <el-icon>
                <Close />
              </el-icon>
              拒绝
            </el-button>
            <!-- 回复按钮 -->
            <el-button size="small" plain class="action-btn" @click="replyComment(row)">
              <el-icon>
                <ChatDotRound />
              </el-icon>
              回复
            </el-button>
            <!-- 更多操作下拉菜单 -->
            <el-dropdown trigger="click">
              <el-button size="small" plain class="action-btn more-btn">
                <el-icon>
                  <MoreFilled />
                </el-icon>
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- 删除选项 -->
                  <el-dropdown-item @click="deleteComment(row.id)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-wrapper">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 回复评论对话框 -->
    <el-dialog v-model="showReplyDialog" title="回复评论" width="500px">
      <el-form :model="replyForm" :rules="replyRules" ref="replyFormRef" label-width="80px">
        <!-- 回复内容输入框 -->
        <el-form-item label="回复内容" prop="content">
          <el-input v-model="replyForm.content" type="textarea" :rows="4" placeholder="请输入回复内容" />
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="showReplyDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReply">提交回复</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 导入Vue 3 Composition API核心功能
import { ref, reactive, computed, onMounted } from 'vue'
// 导入Element Plus组件和消息提示
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入Element Plus图标组件
import { Search, Check, Close, ChatDotRound, Delete, MoreFilled, Loading } from '@element-plus/icons-vue'
// 导入API工具函数
import { get, post, put, del, API_PATHS } from '@/utils/api'

// 类型定义
interface Comment {
  id: number
  content: string
  author: string
  email: string
  postId: number
  postTitle: string
  status: 'pending' | 'approved' | 'rejected'
  createTime: string
  parentId: number | null
}

interface CommentRequest {
  content: string
  author: string
  email: string
  postId: number
  parentId?: number | null
}

interface CommentResponse {
  id: number
  content: string
  author: string
  email: string
  postId: number
  postTitle: string
  status: string
  createTime: string
  parentId: number | null
}

interface CommentStats {
  total: number
  pending: number
  approved: number
  rejected: number
}

interface Post {
  id: number
  title: string
}

interface BatchOperationRequest {
  ids: number[]
}

interface ReplyRequest {
  content: string
  parentId: number
}

// 响应式数据定义
const searchKeyword = ref('') // 搜索关键词
const selectedStatus = ref('') // 选中的状态
const selectedPost = ref('') // 选中的文章
const loading = ref(false) // 页面加载状态
const showReplyDialog = ref(false) // 回复对话框显示状态
const selectedComments = ref<Comment[]>([]) // 选中的评论列表
const currentPage = ref(1) // 当前页码
const pageSize = ref(20) // 每页显示数量
const total = ref(0) // 总数据量
const replyFormRef = ref() // 回复表单引用
const isUsingSampleData = ref(false) // 是否使用示例数据
const isLoading = ref(false) // API加载状态

// 评论数据数组
const comments = ref<Comment[]>([])

// 文章数据数组
const posts = ref<Post[]>([
  { id: 1, title: 'Vue 3 组合式 API 详解' },
  { id: 2, title: '前端性能优化实践' },
  { id: 3, title: 'TypeScript 入门指南' }
])

// 示例数据
const sampleComments: Comment[] = [
  {
    id: 1,
    content: '这篇文章写得很好，对我很有帮助！',
    author: '张三',
    email: 'zhangsan@example.com',
    postId: 1,
    postTitle: 'Vue 3 组合式 API 详解',
    status: 'pending',
    createTime: '2024-01-15 14:30:00',
    parentId: null
  },
  {
    id: 2,
    content: '感谢分享，学到了很多新知识',
    author: '李四',
    email: 'lisi@example.com',
    postId: 1,
    postTitle: 'Vue 3 组合式 API 详解',
    status: 'approved',
    createTime: '2024-01-14 16:20:00',
    parentId: null
  },
  {
    id: 3,
    content: '这个观点很有道理，支持一下',
    author: '王五',
    email: 'wangwu@example.com',
    postId: 2,
    postTitle: '前端性能优化实践',
    status: 'rejected',
    createTime: '2024-01-13 09:15:00',
    parentId: null
  },
  {
    id: 4,
    content: 'TypeScript确实能提高代码质量',
    author: '赵六',
    email: 'zhaoliu@example.com',
    postId: 3,
    postTitle: 'TypeScript 入门指南',
    status: 'pending',
    createTime: '2024-01-12 11:45:00',
    parentId: null
  },
  {
    id: 5,
    content: '期待更多相关内容',
    author: '钱七',
    email: 'qianqi@example.com',
    postId: 2,
    postTitle: '前端性能优化实践',
    status: 'approved',
    createTime: '2024-01-11 15:20:00',
    parentId: null
  }
]

const samplePosts: Post[] = [
  { id: 1, title: 'Vue 3 组合式 API 详解' },
  { id: 2, title: '前端性能优化实践' },
  { id: 3, title: 'TypeScript 入门指南' },
  { id: 4, title: 'React vs Vue 对比分析' },
  { id: 5, title: '现代前端工程化实践' }
]

// 使用示例数据的函数
const useSampleData = () => {
  isUsingSampleData.value = true
  comments.value = [...sampleComments]
  posts.value = [...samplePosts]
  total.value = sampleComments.length
  ElMessage.warning('正在使用示例数据，后端API调用失败')
}

// 回复表单数据对象
const replyForm = reactive({
  content: '', // 回复内容
  parentId: null // 父评论ID
})

// 回复表单验证规则配置
const replyRules = {
  content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

// 计算属性：根据搜索和筛选条件过滤评论列表
const filteredComments = computed(() => {
  return comments.value.filter(comment => {
    // 关键词匹配：检查评论内容和作者是否包含搜索关键词
    const matchKeyword = !searchKeyword.value ||
      comment.content.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      comment.author.toLowerCase().includes(searchKeyword.value.toLowerCase())

    // 状态匹配
    const matchStatus = !selectedStatus.value || comment.status === selectedStatus.value
    // 文章匹配
    const matchPost = !selectedPost.value || comment.postId === Number(selectedPost.value)

    return matchKeyword && matchStatus && matchPost
  })
})

// 方法定义

/**
 * 处理搜索输入
 * 搜索逻辑已在计算属性中处理
 */
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

/**
 * 处理筛选条件变化
 * 筛选逻辑已在计算属性中处理
 */
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

/**
 * 处理表格选择变化
 * 更新选中的评论列表
 * @param selection - 选中的行数据
 */
const handleSelectionChange = (selection: any[]) => {
  selectedComments.value = selection
}

/**
 * 处理分页大小变化
 * @param size - 新的分页大小
 */
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

/**
 * 处理当前页变化
 * @param page - 新的页码
 */
const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

/**
 * 格式化日期显示
 * @param date - 日期字符串
 * @returns 格式化后的本地日期时间字符串
 */
const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN')
}

/**
 * 获取状态对应的标签类型
 * @param status - 评论状态
 * @returns 标签类型
 */
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

/**
 * 获取状态对应的显示文本
 * @param status - 评论状态
 * @returns 显示文本
 */
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

/**
 * 查看文章
 * 跳转到文章详情页面
 * @param postId - 文章ID
 */
const viewPost = (postId: number) => {
  // 跳转到文章详情页
  console.log('查看文章:', postId)
}

/**
 * 通过评论
 * 将评论状态改为已通过
 * @param id - 评论ID
 */
const approveComment = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要通过这条评论吗？', '确认操作', {
      type: 'warning'
    })

    await approveCommentAPI(id)
  } catch {
    // 用户取消操作
  }
}

/**
 * 拒绝评论
 * 将评论状态改为已拒绝
 * @param id - 评论ID
 */
const rejectComment = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要拒绝这条评论吗？', '确认操作', {
      type: 'warning'
    })

    await rejectCommentAPI(id)
  } catch {
    // 用户取消操作
  }
}

/**
 * 删除评论
 * 删除前会显示确认对话框
 * @param id - 要删除的评论ID
 */
const deleteComment = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '确认删除', {
      type: 'warning'
    })

    await deleteCommentAPI(id)
  } catch {
    // 用户取消删除
  }
}

/**
 * 回复评论
 * 打开回复对话框并设置父评论ID
 * @param comment - 要回复的评论对象
 */
const replyComment = (comment: any) => {
  replyForm.parentId = comment.id
  replyForm.content = ''
  showReplyDialog.value = true
}

/**
 * 提交回复
 * 验证回复内容并添加回复评论
 */
const submitReply = async () => {
  try {
    // 验证表单数据
    await replyFormRef.value.validate()

    // 调用API回复评论
    const success = await replyCommentAPI(replyForm.parentId!, replyForm.content)
    if (success) {
      showReplyDialog.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

/**
 * 批量通过评论
 * 将选中的评论状态改为已通过
 */
const batchApprove = async () => {
  try {
    await ElMessageBox.confirm(`确定要通过选中的 ${selectedComments.value.length} 条评论吗？`, '批量操作', {
      type: 'warning'
    })

    const ids = selectedComments.value.map(comment => comment.id)
    const success = await batchApproveAPI(ids)
    if (success) {
      selectedComments.value = []
    }
  } catch {
    // 用户取消操作
  }
}

/**
 * 批量拒绝评论
 * 将选中的评论状态改为已拒绝
 */
const batchReject = async () => {
  try {
    await ElMessageBox.confirm(`确定要拒绝选中的 ${selectedComments.value.length} 条评论吗？`, '批量操作', {
      type: 'warning'
    })

    const ids = selectedComments.value.map(comment => comment.id)
    const success = await batchRejectAPI(ids)
    if (success) {
      selectedComments.value = []
    }
  } catch {
    // 用户取消操作
  }
}

// API调用函数

/**
 * 获取评论列表
 */
const fetchComments = async () => {
  try {
    isLoading.value = true
    
    // 构建查询参数
    const queryParams = new URLSearchParams()
    if (currentPage.value) queryParams.append('page', currentPage.value.toString())
    if (pageSize.value) queryParams.append('size', pageSize.value.toString())
    if (selectedStatus.value) queryParams.append('status', selectedStatus.value)
    if (selectedPost.value) queryParams.append('postId', selectedPost.value.toString())
    if (searchKeyword.value) queryParams.append('keyword', searchKeyword.value)
    
    const url = queryParams.toString() ? `${API_PATHS.COMMENT.LIST}?${queryParams.toString()}` : API_PATHS.COMMENT.LIST
    
    const response = await get(url, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success && response.data) {
      comments.value = response.data.comments || []
      total.value = response.data.total || 0
      isUsingSampleData.value = false
      ElMessage.success('评论列表加载成功')
    } else {
      throw new Error('获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    useSampleData()
  } finally {
    isLoading.value = false
  }
}

/**
 * 获取文章列表（用于筛选）
 */
const fetchPosts = async () => {
  try {
    const response = await get(API_PATHS.COMMENT.POSTS, {
      timeout: 5000,
      retry: 2
    })

    if (response && response.success && response.data) {
      posts.value = response.data || []
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    // 使用示例数据，不显示错误消息
  }
}

/**
 * 通过评论
 */
const approveCommentAPI = async (id: number) => {
  try {
    const response = await post(API_PATHS.COMMENT.APPROVE(id.toString()), {}, {
      timeout: 5000,
      retry: 2
    })

    if (response && response.success) {
      const comment = comments.value.find(c => c.id === id)
      if (comment) {
        comment.status = 'approved'
      }
      ElMessage.success('评论已通过')
    } else {
      throw new Error('通过评论失败')
    }
  } catch (error) {
    console.error('通过评论失败:', error)
    ElMessage.error('通过评论失败，请重试')
  }
}

/**
 * 拒绝评论
 */
const rejectCommentAPI = async (id: number) => {
  try {
    const response = await post(API_PATHS.COMMENT.REJECT(id.toString()), {}, {
      timeout: 5000,
      retry: 2
    })

    if (response && response.success) {
      const comment = comments.value.find(c => c.id === id)
      if (comment) {
        comment.status = 'rejected'
      }
      ElMessage.success('评论已拒绝')
    } else {
      throw new Error('拒绝评论失败')
    }
  } catch (error) {
    console.error('拒绝评论失败:', error)
    ElMessage.error('拒绝评论失败，请重试')
  }
}

/**
 * 删除评论
 */
const deleteCommentAPI = async (id: number) => {
  try {
    const response = await del(API_PATHS.COMMENT.DELETE(id.toString()), {
      timeout: 5000,
      retry: 2
    })

    if (response && response.success) {
      comments.value = comments.value.filter(comment => comment.id !== id)
      ElMessage.success('删除成功')
    } else {
      throw new Error('删除评论失败')
    }
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除评论失败，请重试')
  }
}

/**
 * 回复评论
 */
const replyCommentAPI = async (id: number, content: string) => {
  try {
    const requestData: ReplyRequest = {
      content,
      parentId: id
    }

    const response = await post(API_PATHS.COMMENT.REPLY(id.toString()), requestData, {
      timeout: 5000,
      retry: 2
    })

    if (response && response.success && response.data) {
      const newReply: Comment = {
        id: response.data.id,
        content: response.data.content,
        author: '管理员',
        email: 'admin@example.com',
        postId: response.data.postId,
        postTitle: response.data.postTitle,
        status: 'approved',
        createTime: response.data.createTime,
        parentId: id
      }
      comments.value.unshift(newReply)
      ElMessage.success('回复成功')
      return true
    } else {
      throw new Error('回复评论失败')
    }
  } catch (error) {
    console.error('回复评论失败:', error)
    ElMessage.error('回复评论失败，请重试')
    return false
  }
}

/**
 * 批量通过评论
 */
const batchApproveAPI = async (ids: number[]) => {
  try {
    const requestData: BatchOperationRequest = { ids }
    const response = await post(API_PATHS.COMMENT.BATCH_APPROVE, requestData, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success) {
      ids.forEach(id => {
        const comment = comments.value.find(c => c.id === id)
        if (comment) {
          comment.status = 'approved'
        }
      })
      ElMessage.success('批量通过成功')
      return true
    } else {
      throw new Error('批量通过失败')
    }
  } catch (error) {
    console.error('批量通过失败:', error)
    ElMessage.error('批量通过失败，请重试')
    return false
  }
}

/**
 * 批量拒绝评论
 */
const batchRejectAPI = async (ids: number[]) => {
  try {
    const requestData: BatchOperationRequest = { ids }
    const response = await post(API_PATHS.COMMENT.BATCH_REJECT, requestData, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success) {
      ids.forEach(id => {
        const comment = comments.value.find(c => c.id === id)
        if (comment) {
          comment.status = 'rejected'
        }
      })
      ElMessage.success('批量拒绝成功')
      return true
    } else {
      throw new Error('批量拒绝失败')
    }
  } catch (error) {
    console.error('批量拒绝失败:', error)
    ElMessage.error('批量拒绝失败，请重试')
    return false
  }
}

/**
 * 批量删除评论
 */
const batchDeleteAPI = async (ids: number[]) => {
  try {
    const requestData: BatchOperationRequest = { ids }
    const response = await post(API_PATHS.COMMENT.BATCH_DELETE, requestData, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success) {
      comments.value = comments.value.filter(comment => !ids.includes(comment.id))
      ElMessage.success('批量删除成功')
      return true
    } else {
      throw new Error('批量删除失败')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败，请重试')
    return false
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  // 初始化数据
  fetchComments()
  fetchPosts()
})
</script>

<style scoped lang="scss">
// 导入评论管理页面样式
@use '../../assets/styles/admin/_comments';
</style>